import {ref, toRaw, unref} from 'vue';
import {defineStore} from 'pinia';
import {RouteRecordRaw} from 'vue-router';
import {store} from '@/store';
import {asyncRoutes, constantRouter} from '@/router/index';
import {asyncImportRoute, generatorDynamicRouter} from '@/router/generator-routers';
import {useProjectSetting} from '@/hooks/setting/useProjectSetting';
import {useUserStore} from './user';
import node from "postcss/lib/node";
import {includes} from "lodash-es";
import {iif, of} from "rxjs/dist/types";

interface TreeHelperConfig {
  id: string;
  children: string;
  pid: string;
}

interface MateMenu {
  menuArrs: MateMenu[]
  psDesc: string
  psId: string
  psName: string
  psType: string
  routerUrl: string
}

const DEFAULT_CONFIG: TreeHelperConfig = {
  id: 'id',
  children: 'children',
  pid: 'pid',
};

const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config);

export interface IAsyncRouteState {
  menus: RouteRecordRaw[];
  routers: any[];
  addRouters: any[];
  keepAliveComponents: string[];
  isDynamicAddedRoute: boolean;
}


//白名单
const whitelist = {
  "/dashboard/console": { routerUrl: "/data/dataOverview" },
  "/dashboard/workplace": { routerUrl: "/data/rankManage" }
};
// const whitelist = {
//   "/dashboard/console": {routerUrl: "/dashboard/console"},
//   "/dashboard/workplace": {routerUrl: "/dashboard/workplace"}
// };

function filterMenu<T = any>(tree: T[], mate: Partial<MateMenu>[]): T[] {


  const menuRouter: {} = {};
  Object.assign(menuRouter, whitelist);

  function getMenusList(menus: MateMenu[]) {
    for (let item of menus) {
      menuRouter[item.routerUrl] = item;
      if (item.menuArrs && item.menuArrs.length > 0) {
        getMenusList(item.menuArrs)
      }
    }
  }

  getMenusList(unref(mate));
  console.log(menuRouter);

  function listFilter(list: T[], parentPath: string) {
    parentPath = parentPath.replaceAll("//", "/");
    return list.map((node: any) => ({...node})).filter((node) => {
      node.children = node.children && listFilter(node.children, parentPath + "/" + node.path);
      return func(node, parentPath) || (node.children && node.children.length);
    });
  }

  function func(route: any, path: string): boolean {
    let rpath = route.path;
    if (rpath.indexOf("/") == 0) {
      rpath = path + rpath
    } else {
      rpath = path + "/" + rpath
    }
    if (rpath in menuRouter) {
      if (menuRouter[rpath].psName) {
        route.meta.title = menuRouter[rpath].psName
      }
    }
    return rpath in menuRouter;
  }

  return listFilter(tree, "")
}


export const useAsyncRouteStore = defineStore({
  id: 'app-async-route',
  state: (): IAsyncRouteState => ({
    menus: [],
    routers: constantRouter,
    addRouters: [],
    keepAliveComponents: [],
    // Whether the route has been dynamically added
    isDynamicAddedRoute: false,
  }),
  getters: {
    getMenus(): RouteRecordRaw[] {
      return this.menus;
    },
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    },
  },
  actions: {
    getRouters() {
      return toRaw(this.addRouters);
    },
    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added;
    },
    // 设置动态路由
    setRouters(routers) {
      this.addRouters = routers;
      this.routers = constantRouter.concat(routers);
    },
    setMenus(menus) {
      // 设置动态路由
      this.menus = menus;
    },
    setKeepAliveComponents(compNames) {
      // 设置需要缓存的组件
      this.keepAliveComponents = compNames;
    },
    async generateRoutes() {
      const userStore = useUserStore();
      let accessedRouters;
      // const permissionsList = data.permissions || [];
      // const routeFilter = (route) => {
      //   const { meta } = route;
      //   const { permissions } = meta || {};
      //   if (!permissions) return true;
      //   return permissionsList.some((item) => permissions.includes(item.value));
      // };
      const {getPermissionMode} = useProjectSetting();
      const permissionMode = unref(getPermissionMode);
      if (permissionMode === 'BACK') {
        // 动态获取菜单
        try {
          accessedRouters = await generatorDynamicRouter();
        } catch (error) {
          console.log(error);
        }
      } else {
        try {
          //过滤账户是否拥有某一个权限，并将菜单从加载列表移除
          // accessedRouters = filter(asyncRoutes, routeFilter);
          let userInfo: any = userStore.getUserInfo;
          let mate;
          if (userInfo) {
            mate = userInfo.menus
          }
          if (!mate) {
            userStore.logout()
          }
          //过滤菜单
          accessedRouters = filterMenu(asyncRoutes, mate);
        } catch (error) {
          console.log(error);
        }
      }
      // accessedRouters = accessedRouters.filter(routeFilter);
      // accessedRouters = asyncRoutes;
      this.setRouters(accessedRouters);
      this.setMenus(accessedRouters);
      return toRaw(accessedRouters);
    },
  },
});

// Need to be used outside the setup
export function useAsyncRouteStoreWidthOut() {
  return useAsyncRouteStore(store);
}
